<route lang="json5">
{
  style: {
    navigationBarTitleText: '商品详情',
    navigationBarBackgroundColor: '#018d71',
    navigationBarTextStyle: 'white',
  },
}
</route>

<template>
  <view class="product-detail">
    <!-- 商品轮播图 -->
    <view class="product-gallery">
      <swiper class="gallery-swiper" :indicator-dots="true" :autoplay="false">
        <swiper-item v-for="(image, index) in product.images" :key="index">
          <image :src="image" mode="aspectFill" class="gallery-image" />
        </swiper-item>
      </swiper>
    </view>

    <!-- 商品基本信息 -->
    <view class="product-info-section">
      <view class="product-header">
        <view class="product-title">{{ product.name }}</view>
        <view class="product-subtitle">{{ product.subtitle }}</view>
        <view class="product-tags">
          <text class="tag" v-for="tag in product.tags" :key="tag">{{ tag }}</text>
        </view>
      </view>

      <view class="product-price-section">
        <view class="price-row">
          <text class="current-price">¥{{ selectedSku.price }}</text>
          <text class="original-price" v-if="selectedSku.originalPrice">
            ¥{{ selectedSku.originalPrice }}
          </text>
          <text class="discount" v-if="selectedSku.discount">{{ selectedSku.discount }}折</text>
        </view>
        <view class="sales-info">
          <text class="sales">销量 {{ product.sales }}</text>
          <text class="rating">评分 {{ product.rating }}</text>
        </view>
      </view>
    </view>

    <!-- 规格选择 -->
    <view class="spec-section">
      <view class="section-title">规格选择</view>
      <view class="spec-options">
        <view class="spec-option" v-for="spec in product.specs" :key="spec.name">
          <view class="spec-name">{{ spec.name }}</view>
          <view class="spec-values">
            <view
              class="spec-value"
              v-for="value in spec.values"
              :key="value.id"
              :class="{ active: selectedSpecs[spec.name] === value.id }"
              @click="selectSpec(spec.name, value.id)"
            >
              {{ value.name }}
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 数量选择 -->
    <view class="quantity-section">
      <view class="section-title">购买数量</view>
      <view class="quantity-control">
        <wd-button size="small" @click="decreaseQuantity" :disabled="quantity <= 1">-</wd-button>
        <text class="quantity">{{ quantity }}</text>
        <wd-button size="small" @click="increaseQuantity">+</wd-button>
      </view>
    </view>

    <!-- 商品详情 -->
    <view class="detail-section">
      <view class="section-title">商品详情</view>
      <view class="detail-content">
        <view class="detail-item" v-for="(detail, index) in product.details" :key="index">
          <text class="detail-label">{{ detail.label }}</text>
          <text class="detail-value">{{ detail.value }}</text>
        </view>
      </view>
    </view>

    <!-- 底部操作栏 -->
    <view class="bottom-actions">
      <view class="action-left">
        <view class="action-item" @click="toggleFavorite">
          <view class="action-icon" :class="{ active: isFavorite }">
            <text class="icon-text">{{ isFavorite ? '❤️' : '🤍' }}</text>
          </view>
          <text class="action-text">{{ isFavorite ? '已收藏' : '收藏' }}</text>
        </view>
        <view class="action-item" @click="shareProduct">
          <view class="action-icon">
            <text class="icon-text">📤</text>
          </view>
          <text class="action-text">分享</text>
        </view>
        <view class="action-item" @click="contactService">
          <view class="action-icon">
            <text class="icon-text">💬</text>
          </view>
          <text class="action-text">客服</text>
        </view>
      </view>

      <view class="action-right">
        <view class="cart-btn" @click="addToCart">
          <text class="btn-icon">🛒</text>
          <text class="btn-text">购物车</text>
        </view>
        <wd-button type="primary" @click="buyNow" class="buy-btn">立即购买</wd-button>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useOrderStore } from '@/store/orderConfim'

// 获取订单store
const orderStore = useOrderStore()

// 商品数据
const product = ref({
  id: 1,
  name: '红富士苹果',
  subtitle: '新鲜采摘，甜脆可口，果肉细腻',
  images: [
    '/static/images/products/apple1.jpg',
    '/static/images/products/apple2.jpg',
    '/static/images/products/apple3.jpg',
    '/static/images/products/apple4.jpg',
  ],
  tags: ['热销', '新鲜', '无农药'],
  sales: 1250,
  rating: 4.8,
  specs: [
    {
      name: '规格',
      values: [
        { id: 1, name: '小果(3-4个/斤)', price: 12.8, originalPrice: 15.9 },
        { id: 2, name: '中果(2-3个/斤)', price: 15.8, originalPrice: 19.9 },
        { id: 3, name: '大果(1-2个/斤)', price: 18.8, originalPrice: 22.9 },
      ],
    },
    {
      name: '包装',
      values: [
        { id: 1, name: '散装', price: 0, originalPrice: 0 },
        { id: 2, name: '精美礼盒', price: 5.0, originalPrice: 8.0 },
      ],
    },
  ],
  details: [
    { label: '产地', value: '山东烟台' },
    { label: '品种', value: '红富士' },
    { label: '规格', value: '中果(2-3个/斤)' },
    { label: '保质期', value: '7天' },
    { label: '储存方式', value: '冷藏保存' },
    { label: '营养成分', value: '富含维生素C、膳食纤维' },
  ],
})

// 选中的规格
const selectedSpecs = ref({
  规格: 2,
  包装: 1,
})

// 购买数量
const quantity = ref(1)

// 计算选中的SKU
const selectedSku = computed(() => {
  const specOption = product.value.specs[0].values.find((v) => v.id === selectedSpecs.value['规格'])
  const packageOption = product.value.specs[1].values.find(
    (v) => v.id === selectedSpecs.value['包装'],
  )

  return {
    price: (specOption?.price || 0) + (packageOption?.price || 0),
    originalPrice: (specOption?.originalPrice || 0) + (packageOption?.originalPrice || 0),
    discount: specOption?.originalPrice
      ? Math.round(
          ((specOption.price + (packageOption?.price || 0)) /
            (specOption.originalPrice + (packageOption?.originalPrice || 0))) *
            10,
        )
      : null,
  }
})

// 选择规格
const selectSpec = (specName: string, valueId: number) => {
  selectedSpecs.value[specName] = valueId
}

// 增加数量
const increaseQuantity = () => {
  quantity.value++
}

// 减少数量
const decreaseQuantity = () => {
  if (quantity.value > 1) {
    quantity.value--
  }
}

// 加入购物车
const addToCart = () => {
  const cartItem = {
    id: product.value.id,
    name: product.value.name,
    image: product.value.images[0],
    price: selectedSku.value.price,
    quantity: quantity.value,
    specText: getSpecText(),
    selected: true,
  }

  // 这里可以添加购物车数据存储逻辑
  // 目前先跳转到购物车页面
  uni.showToast({
    title: '已加入购物车',
    icon: 'success',
  })

  // 延迟跳转到购物车页面
  //   setTimeout(() => {
  //     uni.switchTab({
  //       url: '/pages/cart/index',
  //     })
  //   }, 1000)

  console.log('加入购物车:', cartItem)
}

// 立即购买
const buyNow = () => {
  const orderItem = {
    id: product.value.id,
    name: product.value.name,
    image: product.value.images[0],
    specText: getSpecText(),
    quantity: quantity.value,
    price: selectedSku.value.price,
    totalPrice: selectedSku.value.price * quantity.value,
  }

  // 使用Pinia store保存订单数据
  orderStore.setOrderItems([orderItem])

  // 跳转到订单确认页面
  uni.navigateTo({
    url: '/pages/order/confirm',
  })
}

// 收藏状态
const isFavorite = ref(false)

// 切换收藏状态
const toggleFavorite = () => {
  isFavorite.value = !isFavorite.value
  uni.showToast({
    title: isFavorite.value ? '已收藏' : '已取消收藏',
    icon: isFavorite.value ? 'success' : 'none',
  })
}

// 分享商品
const shareProduct = () => {
  uni.showToast({
    title: '分享功能开发中',
    icon: 'none',
  })
}

// 联系客服
const contactService = () => {
  uni.showToast({
    title: '客服功能开发中',
    icon: 'none',
  })
}
// 获取规格文本
const getSpecText = () => {
  const specTexts = []
  for (const [specName, specValue] of Object.entries(selectedSpecs.value)) {
    const spec = product.value.specs.find((s) => s.name === specName)
    const value = spec?.values.find((v) => v.id === specValue)
    if (value) {
      specTexts.push(`${specName}: ${value.name}`)
    }
  }
  return specTexts.join(', ')
}

onMounted(() => {
  console.log('商品详情页面加载完成')
})
</script>

<style lang="scss" scoped>
.product-detail {
  background-color: #f8f8f8;
  min-height: 100vh;
  padding-bottom: 80px;
}

.product-gallery {
  background: #fff;
  margin-bottom: 8px;

  .gallery-swiper {
    height: 300px;

    .gallery-image {
      width: 100%;
      height: 100%;
    }
  }
}

.product-info-section {
  background: #fff;
  padding: 16px;
  margin-bottom: 8px;

  .product-header {
    margin-bottom: 16px;

    .product-title {
      font-size: 20px;
      font-weight: 600;
      color: #333;
      margin-bottom: 8px;
    }

    .product-subtitle {
      font-size: 14px;
      color: #666;
      margin-bottom: 12px;
    }

    .product-tags {
      display: flex;
      gap: 8px;

      .tag {
        background: #fff2e8;
        color: #ff6b35;
        font-size: 12px;
        padding: 4px 8px;
        border-radius: 12px;
      }
    }
  }

  .product-price-section {
    .price-row {
      display: flex;
      align-items: center;
      margin-bottom: 8px;

      .current-price {
        font-size: 24px;
        font-weight: 600;
        color: #ff4757;
        margin-right: 12px;
      }

      .original-price {
        font-size: 14px;
        color: #999;
        text-decoration: line-through;
        margin-right: 8px;
      }

      .discount {
        background: #ff4757;
        color: #fff;
        font-size: 12px;
        padding: 2px 6px;
        border-radius: 4px;
      }
    }

    .sales-info {
      display: flex;
      gap: 16px;

      .sales,
      .rating {
        font-size: 12px;
        color: #999;
      }
    }
  }
}

.spec-section {
  background: #fff;
  padding: 16px;
  margin-bottom: 8px;

  .section-title {
    font-size: 16px;
    font-weight: 600;
    color: #333;
    margin-bottom: 12px;
  }

  .spec-options {
    .spec-option {
      margin-bottom: 16px;

      .spec-name {
        font-size: 14px;
        color: #666;
        margin-bottom: 8px;
      }

      .spec-values {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;

        .spec-value {
          padding: 8px 12px;
          border: 1px solid #e0e0e0;
          border-radius: 6px;
          font-size: 14px;
          color: #333;
          transition: all 0.3s ease;

          &.active {
            border-color: #018d71;
            background: #018d71;
            color: #fff;
          }
        }
      }
    }
  }
}

.quantity-section {
  background: #fff;
  padding: 16px;
  margin-bottom: 8px;

  .section-title {
    font-size: 16px;
    font-weight: 600;
    color: #333;
    margin-bottom: 12px;
  }

  .quantity-control {
    display: flex;
    align-items: center;
    gap: 16px;

    .quantity {
      font-size: 16px;
      font-weight: 600;
      color: #333;
      min-width: 40px;
      text-align: center;
    }
  }
}

.detail-section {
  background: #fff;
  padding: 16px;

  .section-title {
    font-size: 16px;
    font-weight: 600;
    color: #333;
    margin-bottom: 12px;
  }

  .detail-content {
    .detail-item {
      display: flex;
      justify-content: space-between;
      padding: 8px 0;
      border-bottom: 1px solid #f0f0f0;

      &:last-child {
        border-bottom: none;
      }

      .detail-label {
        font-size: 14px;
        color: #666;
      }

      .detail-value {
        font-size: 14px;
        color: #333;
      }
    }
  }
}

// 美化后的底部操作栏
.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  padding: 0px 16px;
  border-top: 1px solid #f0f0f0;
  z-index: 100;

  display: flex;
  justify-content: space-between;
  align-items: center;

  .action-left {
    display: flex;

    .action-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 4px;
      padding: 8px;
      border-radius: 8px;
      transition: all 0.3s ease;

      &:active {
        background: #f5f5f5;
        transform: scale(0.95);
      }

      .action-icon {
        width: 32px;
        height: 32px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 50%;
        background: #f8f8f8;
        transition: all 0.3s ease;

        &.active {
          background: #ffe6e6;
          animation: pulse 0.6s ease-in-out;
        }

        .icon-text {
          font-size: 16px;
        }
      }

      .action-text {
        font-size: 10px;
        color: #666;
        text-align: center;
      }
    }
  }

  .action-right {
    display: flex;
    gap: 12px;
    flex: 1;

    .cart-btn {
      flex: 1;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      background: linear-gradient(135deg, #fff2e8, #ffe4d6);
      border: 1px solid #ff6b35;
      border-radius: 12px;
      transition: all 0.3s ease;

      &:active {
        transform: scale(0.98);
        box-shadow: 0 2px 8px rgba(255, 107, 53, 0.3);
      }

      .btn-icon {
        font-size: 18px;
        margin-bottom: 2px;
      }

      .btn-text {
        font-size: 11px;
        color: #ff6b35;
        font-weight: 500;
      }
    }

    .buy-btn {
      flex: 2;
      height: 48px;
      font-size: 16px;
      font-weight: 600;
      border-radius: 12px;
      background: linear-gradient(135deg, #018d71, #00b894);
      border: none;
      box-shadow: 0 4px 12px rgba(1, 141, 113, 0.3);
      transition: all 0.3s ease;

      &:active {
        transform: scale(0.98);
        box-shadow: 0 2px 8px rgba(1, 141, 113, 0.4);
      }
    }
  }
}

// 收藏动画
@keyframes pulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.1);
  }
  100% {
    transform: scale(1);
  }
}

@media (max-width: 375px) {
  .product-gallery .gallery-swiper {
    height: 250px;
  }

  .bottom-actions {
    padding: 8px 12px;

    .action-buttons {
      gap: 8px;

      .buy-btn {
        height: 44px;
        font-size: 14px;
      }
    }
  }
}
</style>
